package starfield.util;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

public class JFileSaver extends JFileChooser {
	@Override
    public void approveSelection(){
        File file = getSelectedFile();
		
		if (getFileFilter() instanceof FileNameExtensionFilter) {
			String[] exts = ((FileNameExtensionFilter)getFileFilter()).getExtensions();
			
			boolean hasValidExtension = false;
			
			for (String ext : exts) {
				if (file.getName().endsWith('.' + ext.toLowerCase())) {
					hasValidExtension = true;
					break;
				}
			}
			
			if (!hasValidExtension) {
				file = new File(file.toString() + '.' + exts[0]);
				setSelectedFile(file);
			}
		}
		
        if (file.exists() && getDialogType() == SAVE_DIALOG) {
            int result = JOptionPane.showConfirmDialog(
					this, 
					"The file '" + file.getName() + "' already exists. Do you want to overwrite it?", 
					getDialogTitle(), 
					JOptionPane.YES_NO_CANCEL_OPTION);
			
            switch (result) {
                case JOptionPane.YES_OPTION:
                    super.approveSelection();
					break;
					
                case JOptionPane.NO_OPTION:
					break;
					
                case JOptionPane.CLOSED_OPTION:
					break;
					
                case JOptionPane.CANCEL_OPTION:
                    cancelSelection();
					break;
            }
        } else {
			super.approveSelection();
		}
    }
}
